<?php

include  APP_PATH.'Common/App/common.php';


define ( 'Pager',10);


// 加密算法
function pwdHash($password) {
	return md5 ( md5 ( trim ( $password ) . C ( 'KEYCODE' ) ) . C ( 'KEYCODE' ) );
}

/**
  +----------------------------------------------------------
 * 加密密码
  +----------------------------------------------------------
 * @param string    $data   待加密字符串
  +----------------------------------------------------------
 * @return string 返回加密后的字符串
 */
function encrypt($data) {
    return md5(C("AUTH_CODE") . md5($data));
}

/**
 +-----------------------------------------------------------------------------------------
 * 删除目录及目录下所有文件或删除指定文件
 +-----------------------------------------------------------------------------------------
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 +-----------------------------------------------------------------------------------------
 * @return bool 返回删除状态
 +-----------------------------------------------------------------------------------------
 */
function delDirAndFile($path, $delDir = FALSE) {
	$handle = opendir($path);
	if ($handle) {
		while (false !== ( $item = readdir($handle) )) {
			if ($item != "." && $item != "..")
				is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
		}
		closedir($handle);
		if ($delDir)
			return rmdir($path);
	}else {
		if (file_exists($path)) {
			return unlink($path);
		} else {
			return FALSE;
		}
	}
}


/**
 * 遍历获取目录下的指定类型的文件
 * @param $path
 * @param array $files
 * @return array
 */




 function getfiles( $path , &$files = array() )
{
	if ( !is_dir( $path ) ) return null;
	$handle = opendir( $path );
	while ( false !== ( $file = readdir( $handle ) ) ) {
		if ( $file != '.' && $file != '..' ) {
			$path2 = $path . '/' . $file;
			if ( is_dir( $path2 ) ) {
				getfiles( $path2 , $files );
			} else {
				if ( preg_match( "/\.(gif|jpeg|jpg|png|bmp)$/i" , $file ) ) {
					$files[] = $path2;
				}
			}
		}
	}
	return $files;
}





function is_top($i) {
	if ($i==1) {
		echo  '【固顶】';
	}
}

function is_empty($test) {
	if ($test=='') {
		echo '空' ;
	}else {
		echo $test ;
	}
}
/*
function getAuthorByID($ID) {
	$Users = M ( 'Users' );
	$res = $Users->find ( $ID );
	return $res;
}

function getAuthorNameByID($ID) {
	$Users = M ( 'Users' );
	$res = $Users->find ( $ID );
	return $res ['user_nicename'];
}

function getAuthorUrlByID($ID) {
	$Users = M ( 'Users' );
	$res = $Users->find ( $ID );
	return $res ['user_url'];
}
function getAuthoreEmailByID($ID) {
	$Users = M ( 'Users' );
	$res = $Users->find ( $ID );
	return $res ['user_email'];
}*/

function getTimestamp($Timestamp, $need = '$timestamp') {
	$array = explode ( "-", $Timestamp );
	$year = $array [0];
	$month = $array [1];
	
	$array = explode ( ":", $array [2] );
	$minute = $array [1];
	$second = $array [2];
	
	$array = explode ( " ", $array [0] );
	$day = $array [0];
	$hour = $array [1];
	
	$timestamp = mktime ( $hour, $minute, $second, $month, $day, $year );
	
	if ($need === 'hour') {
		return $hour;
	} else if ($need === 'minute') {
		return $minute;
	} else if ($need === 'second') {
		return $second;
	} else if ($need === 'month') {
		return $month;
	} else if ($need === 'day') {
		return $day;
	} else if ($need === 'year') {
		return $year;
	}

}
	
/*
function do_post($url, $data) {
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
	curl_setopt ( $ch, CURLOPT_POST, TRUE );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	$ret = curl_exec ( $ch );

	curl_close ( $ch );
	return $ret;
}
*/

/**
 * 打印数组
 */
function print_array($res){
		
	echo '<pre>';
	print_r($res);
	echo '</pre>';
		
		
}

/**
 * 数组降维
 */
function array_to_str($res) {
	foreach ($res as $each){
		$str.=$each.',';
	}
	return $str;
}


/**
 * 二位数组转化为一维数组
 * @param 二维数组
 * @return 一维数组
 */
function array_multi2single($array) {

	static $result_array = array ();
	foreach ( $array as $value ) {
		if (is_array ( $value )) {
			array_multi2single ( $value );
		} else
			$result_array [] = $value;
	}
	return $result_array;
}



/**
 *
 * @package 二维数组排序
 * @version $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $
 *
 *
 *          Sort an two-dimension array by some level two items use
 *          array_multisort() function.
 *
 *
 *
 *          sysSortArray($Array,&quot;Key1&quot;,&quot;SORT_ASC&quot;,&quot;SORT_RETULAR&quot;,&quot;Key2&quot;……)
 * @param array $ArrayData
 *        	the array to sort.
 * @param string $KeyName1
 *        	the first item to sort by.
 * @param string $SortOrder1
 *        	the order to sort by(&quot;SORT_ASC&quot;|&quot;SORT_DESC&quot;)
 * @param string $SortType1
 *        	the sort
 *        	type(&quot;SORT_REGULAR&quot;|&quot;SORT_NUMERIC&quot;|&quot;SORT_STRING&quot;)
 * @return array sorted array.
 */
function sysSortArray($ArrayData, $KeyName1, $SortOrder1 = "SORT_ASC", $SortType1 = "SORT_REGULAR") {
	if (! is_array ( $ArrayData )) {
		return $ArrayData;
	}

	// Get args number.
	$ArgCount = func_num_args ();

	// Get keys to sort by and put them to SortRule array.
	for($I = 1; $I < $ArgCount; $I ++) {
		$Arg = func_get_arg ( $I );
		if (! eregi ( "SORT", $Arg )) {
			$KeyNameList [] = $Arg;
			$SortRule [] = '$' . $Arg;
		} else {
			$SortRule [] = $Arg;
		}
	}

	// Get the values according to the keys and put them to array.
	foreach ( $ArrayData as $Key => $Info ) {
		foreach ( $KeyNameList as $KeyName ) {
			${
				$KeyName} [$Key] = $Info [$KeyName];
		}
	}

	// Create the eval string and eval it.
	$EvalString = 'array_multisort(' . join ( ",", $SortRule ) . ',$ArrayData);';
	eval ( $EvalString );
	return $ArrayData;
}

/**
 * 获取二位数组分组 参数 $arr需要处理的数组，$key_field 分类key值
 */
function groupBy($arr, $key_field) {
	$ret = array ();
	foreach ( ($arr) as $row ) {
		$key = $row [$key_field];
		$ret [$key] [] = $row;
	}
	return ($ret);
}



/*
 * 百分比 输入数字 输出百分比
*/
function percent($num) {
	// return $num;
	return sprintf ( '%.2f%%', $num * 100 );
}



function check_verify() {
	if (!APP_DEBUG) {
		if ($_SESSION ['verify'] != md5 ( $_POST ['verify'] )) {
			$this->error ( '验证码错误！' );
		}
	}

}
/*
function p($str) {
	dump($str, 1, '<pre>', 0);
}
*/
/**
  +----------------------------------------------------------
 * 功能：检测一个目录是否存在，不存在则创建它
  +----------------------------------------------------------
 * @param string    $path      待检测的目录
  +----------------------------------------------------------
 * @return boolean
  +----------------------------------------------------------
 */
function makeDir($path) {
    return is_dir($path) or (makeDir(dirname($path)) and @mkdir($path, 0777));
}

/**
  +----------------------------------------------------------
 * 功能：检测一个字符串是否是邮件地址格式
  +----------------------------------------------------------
 * @param string $value    待检测字符串
  +----------------------------------------------------------
 * @return boolean
  +----------------------------------------------------------
 */
function is_email($value) {
    return preg_match("/^[0-9a-zA-Z]+(?:[\_\.\-][a-z0-9\-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+$/i", $value);
}

/**
  +----------------------------------------------------------
 * 功能：系统邮件发送函数
  +----------------------------------------------------------
 * @param string $to    接收邮件者邮箱
 * @param string $name  接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body    邮件内容
 * @param string $attachment 附件列表
  +----------------------------------------------------------
 * @return boolean
  +----------------------------------------------------------
 */
function send_mail($to, $name, $subject = '', $body = '', $attachment = null, $config = '') {
    // $config = is_array($config) ? $config : C('SYSTEM_EMAIL');
    //从数据库读取smtp配置
    $config = array(
        'smtp_host'  => C('smtp_host'),
        'smtp_port'  => C('smtp_port'),
        'smtp_user'  => C('smtp_user'),
        'smtp_pass'  => C('smtp_pass'),
        'from_email' => C('from_email'),
        'from_name'  => C('OUR_NAME')
        );
    
   // Log::write(array_to_str($config));
    include C('PHPMailer');      //从PHPMailer目录导class.phpmailer.php类文件
    $mail = new PHPMailer();                           //PHPMailer对象
    $mail->CharSet = 'UTF-8';                         //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                                   // 设定使用SMTP服务
//    $mail->IsHTML(true);
    $mail->SMTPDebug = 1;                             // 关闭SMTP调试功能 1 = errors and messages2 = messages only
    $mail->SMTPAuth = true;                           // 启用 SMTP 验证功能
    if ($config['smtp_port'] == 465)
        $mail->SMTPSecure = 'ssl';                    // 使用安全协议
    $mail->Host = $config['smtp_host'];                // SMTP 服务器
    $mail->Port = $config['smtp_port'];                // SMTP服务器的端口号
    $mail->Username = $config['smtp_user'];           // SMTP服务器用户名
    $mail->Password = $config['smtp_pass'];           // SMTP服务器密码
    $mail->SetFrom($config['from_email'], $config['from_name']);
    $replyEmail = $config['reply_email'] ? $config['reply_email'] : $config['reply_email'];
    $replyName = $config['reply_name'] ? $config['reply_name'] : $config['reply_name'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            if (is_array($file)) {
                is_file($file['path']) && $mail->AddAttachment($file['path'], $file['name']);
            } else {
                is_file($file) && $mail->AddAttachment($file);
            }
        }
    } else {
        is_file($attachment) && $mail->AddAttachment($attachment);
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
  +----------------------------------------------------------
 * 功能：剔除危险的字符信息
  +----------------------------------------------------------
 * @param string $val
  +----------------------------------------------------------
 * @return string 返回处理后的字符串
  +----------------------------------------------------------
 */
function remove_xss($val) {
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <java\0script>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=@avascript:alert('XSS')>
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
        // @ @ search for the hex values
        $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
    }

    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);

    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }
    return $val;
}

/**
  +----------------------------------------------------------
 * 功能：计算文件大小
  +----------------------------------------------------------
 * @param int $bytes
  +----------------------------------------------------------
 * @return string 转换后的字符串
  +----------------------------------------------------------
 */
function byteFormat($bytes) {
    $sizetext = array(" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    return round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), 2) . $sizetext[$i];
}

function checkCharset($string, $charset = "UTF-8") {
    if ($string == '')
        return;
    $check = preg_match('%^(?:
                                [\x09\x0A\x0D\x20-\x7E] # ASCII
                                | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
                                | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
                                | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
                                | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
                                | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
                                | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
                                | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
                                )*$%xs', $string);

    return $charset == "UTF-8" ? ($check == 1 ? $string : iconv('gb2312', 'utf-8', $string)) : ($check == 0 ? $string : iconv('utf-8', 'gb2312', $string));
}

/**
  +----------------------------------------------------------
 * 生成随机字符串
  +----------------------------------------------------------
 * @param int       $length  要生成的随机字符串长度
 * @param string    $type    随机码类型：0，数字+大写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
  +----------------------------------------------------------
 * @return string
  +----------------------------------------------------------
 */
function randCode($length = 5, $type = 0) {
    $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } else if ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $str[$i] = $string[rand(0, $count)];
        $code .= $str[$i];
    }
    return $code;
}

function del_sql($name) {
    return str_replace('.sql', '', $name);
}

function del_zip($name) {
	return str_replace('.zip', '', $name);
}